package com.rdc.example.service.impl;

import com.rdc.example.bean.Result;
import com.rdc.example.dao.PlayListDao;
import com.rdc.example.dao.PlayListSongDao;
import com.rdc.example.dao.SongDao;
import com.rdc.example.dao.SongLikesDao;
import com.rdc.example.dao.impl.PlayListDaoImpl;
import com.rdc.example.dao.impl.PlayListSongDaoImpl;
import com.rdc.example.dao.impl.SongDaoImpl;
import com.rdc.example.dao.impl.SongLikesDaoImpl;


public class SongLikesServiceImpl implements com.rdc.example.service.SongLikesService {
    SongLikesDao songLikesDao=new SongLikesDaoImpl();
    PlayListDao playListDao=new PlayListDaoImpl();
    PlayListSongDao playListSongDao=new PlayListSongDaoImpl();

    @Override
    public Result turnSongLike(Integer userId, Integer songId) throws Exception {
        if (userId == null || songId == null) {
            return Result.fail("songId或userId为空", null);
        }
        SongDao songDao = new SongDaoImpl();
        if (songLikesDao.checkSongLike(userId, songId)) {
             //点赞了，取消
            boolean likeDeleted = songLikesDao.deleteSongLike(userId, songId);
            if (!likeDeleted) {
                return Result.fail("取消点赞失败，请重试",null);
            }
            //song.likes--
            boolean likeReduced = songDao.reduceLike(songId);
            if (!likeReduced) {
                return Result.fail("点赞数更新失败",null);
            }
             //移除红心歌单
            Integer playListId = playListDao.getRedHeartPlayListIdByUserId(userId);
            if (playListId != null) {
                boolean playlistUpdated = playListSongDao.delete(playListId, songId);
                if (!playlistUpdated) {
                    return Result.fail("红心歌单更新失败",null);
                }
            }
            return Result.success("成功取消点赞",null);

        } else {
            //没点，要点赞
            boolean likeInsert = songLikesDao.insertSongLike(userId, songId);
            if (!likeInsert) {
                return Result.fail("点赞失败，请重试",null);
            }
            //song.likes--
            boolean likeAdd = songDao.addLike(songId);
            if (!likeAdd) {
                return Result.fail("点赞数更新失败",null);
            }
            //移除红心歌单
            Integer playListId = playListDao.getRedHeartPlayListIdByUserId(userId);
            if (playListId != null) {
                boolean playlistUpdated = playListSongDao.insert(playListId, songId);
                if (!playlistUpdated) {
                    return Result.fail("红心歌单更新失败",null);
                }
            }
            return Result.success("成功点赞",null);
        }
    }



}
